package com.github.serezhka.airplay.player.gstreamer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.formdev.flatlaf.FlatDarkLaf;
import com.github.serezhka.airplay.lib.VideoStreamInfo;
import com.csmk.control.MKSApi;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.freedesktop.gstreamer.Gst;
import org.freedesktop.gstreamer.Pipeline;
import org.freedesktop.gstreamer.elements.AppSink;
import org.freedesktop.gstreamer.swing.GstVideoComponent;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

@Slf4j
public class GstPlayerSwing extends GstPlayer {

    private MKSApi mksApi = new MKSApi();

    private GstVideoComponent vc;

    static {
        FlatDarkLaf.setup();
    }

    private final JFrame window;
    // TODO swing 入口
    public GstPlayerSwing() {
        AppSink sink = (AppSink) h264Pipeline.getElementByName("sink");
        vc = new GstVideoComponent(sink);

        window = new JFrame(ScreenConfig.title);
        window.setLayout(new BorderLayout()); // 确保内容填充布局
        window.add(vc, BorderLayout.CENTER); // 视频组件填充整个窗口内容区域
        window.setResizable(false);
        // 确保窗口和内容一致
        vc.setPreferredSize(new Dimension(375, 667));
        vc.addMouseListener(new GstMouseListener(mksApi));
        vc.addMouseMotionListener(new GstMouseMotionListener(mksApi));
        window.addKeyListener(new GstKeyListener(mksApi));
        window.pack();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    protected Pipeline createH264Pipeline() {
        return (Pipeline) Gst.parseLaunch("appsrc name=h264-src ! h264parse ! avdec_h264 ! videoconvert ! appsink name=sink sync=false");
    }

    @Override
    public void onVideoFormat(VideoStreamInfo videoStreamInfo) {
        mksApi.setDeviceIp(videoStreamInfo.getDeviceIP());
        mksApi.getScreenSize(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                log.error("请求失败",e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String body = response.body().string();
                log.info("请求成功:{}",body);
                JSONObject sizeInfo = JSON.parseObject(body);
                String[] data = sizeInfo.getString("data").split(";;");
                vc.setPreferredSize(new Dimension((int)Float.parseFloat(data[0])/ScreenConfig.scale,(int)Float.parseFloat(data[1])/ScreenConfig.scale));
                window.pack();
                window.setVisible(true);
            }
        });

        super.onVideoFormat(videoStreamInfo);
    }

    @Override
    public void onVideoSrcDisconnect() {
        window.setVisible(false);
        super.onVideoSrcDisconnect();
    }
}
